<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="diaTitle"
      width="700"
      class="dialogStyle"
      @close="handleClose"
    >
      <div class="h-65vh overflow-auto">
        <el-form
          :model="formParams"
          :rules="rulesForm"
          label-width="110px"
          ref="ruleFormRef"
        >
          <el-row :span="24">
            <el-col :span="11">
              <el-select
                clearable
                class="w-full"
                v-model="formParams.type"
                placeholder="请选择回访方式"
              >
                <el-option
                  v-for="(dict, index) in followup_method"
                  :key="index"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="11" :offset="2">
              <el-date-picker
                clearable
                style="width: 100%"
                v-model="formParams.followTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择回访时间"
              />
            </el-col>
            <el-col :span="24" class="mt-20px mb-20px">
              <el-input
                v-model="formParams.content"
                type="textarea"
                rows="5"
                maxlength="300"
                placeholder="请输入回访内容"
              />
            </el-col>
          </el-row>
          <el-form-item label="上传附件：">
            <el-upload
              v-model:file-list="formParams.fileList"
              class="upload-demo"
              action="#"
              :before-upload="beforeAvatarUpload"
              :http-request="handleFileChange"
              accept=".rar, .zip, .doc, .docx, .pdf"
              :show-file-list="false"
            >
              <el-button type="default" style="font-size: 14px"
                ><el-icon><UploadFilled /></el-icon>上传</el-button
              >
              <template #tip>
                <div class="el-upload__tip float-right">
                  支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
                </div>
              </template>
            </el-upload>
            <div class="text-14px mt-10px" style="width: 100%">
              <div v-for="(item, index) in fileList" :key="item.fileId">
                <a :href="item.url" target="_blank" class="text-#409eff">{{
                  item.origFileName
                }}</a>
                <el-button text plain @click="delFileName(index)"
                  >删除</el-button
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item
            label="客户名称："
            prop="customerName"
            v-if="dialogParam.tableName != 'biz_contact'"
          >
            <el-input v-model="formParams.customerName" disabled type="input" />
          </el-form-item>
          <!-- 订单模块 start -->
          <div
            v-if="
              dialogParam.tableName == 'ord_order' ||
              dialogParam.tableName == 'ord_purchase_order' ||
              dialogParam.tableName == 'ord_inner_order'
            "
          >
            <el-form-item label="订单标题：" prop="orderTitle">
              <el-input v-model="formParams.orderTitle" disabled type="input" />
            </el-form-item>
            <el-form-item label="回访产品：" prop="productId">
              <el-select
                clearable
                v-model="formParams.productId"
                placeholder="请选择产品"
                style="width: 100%"
                disabled
              >
                <el-option
                  v-for="(dict, index) in productList"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系人" prop="mainContactName">
              <el-input
                v-model="formParams.mainContactName"
                type="input"
                placeholder="请输入联系人"
              />
            </el-form-item>
            <el-form-item label="联系电话" prop="mainContactPhone">
              <el-input
                v-model="formParams.mainContactPhone"
                type="input"
                placeholder="请输入联系电话"
              />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="formParams.address"
                type="input"
                placeholder="请输入地址"
              />
            </el-form-item>
            <el-form-item label="更新客户信息" prop="renew">
              <el-checkbox v-model="formParams.renew" size="large" />
            </el-form-item>
          </div>
          <!-- 订单模块 end -->
          <!-- 客户模块 商机模块 start -->
          <div
            v-else-if="
              dialogParam.tableName == 'biz_customer' ||
              dialogParam.tableName == 'ord_business_opportunity'
            "
          >
            <el-form-item
              :label="
                dialogParam.tableName == 'biz_customer'
                  ? '客户状态：'
                  : '商机阶段：'
              "
              prop="status"
            >
              <el-select
                v-if="dialogParam.tableName == 'biz_customer'"
                clearable
                v-model="formParams.status"
                placeholder="请选择客户状态"
                style="width: 100%"
              >
                <el-option
                  v-for="(dict, index) in customer_status"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
              <el-select
                v-else
                clearable
                v-model="formParams.status"
                placeholder="请选择商机阶段"
                style="width: 100%"
              >
                <el-option
                  v-for="(dict, index) in business_stage"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系人：" prop="linkId">
              <el-select
                v-model="formParams.linkId"
                placeholder="请选择联系人"
                class="w-full"
                clearable
                filterable
                @change="contactsChange"
                remote
                :remote-method="queryContacts"
              >
                <el-option
                  v-for="item in contactsOptions"
                  :key="item.id"
                  :label="item.contactName"
                  :value="item.id"
                >
                  <div>
                    <span>{{ item.contactName }}</span>
                    <span>{{
                      item.contactNumber ? '(' + item.contactNumber + ')' : ''
                    }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 客户模块 商机模块 end -->
          <!-- 联系人 start-->
          <div v-else-if="dialogParam.tableName == 'biz_contact'">
            <el-form-item label="联系人：" prop="linkName">
              <el-input v-model="formParams.linkName" disabled type="input" />
            </el-form-item>
          </div>
          <!-- 联系人 end-->
          <!-- 项目模块 start -->
          <div v-else-if="dialogParam.tableName == 'ord_project'">
            <el-form-item label="项目名称：" prop="proName">
              <el-input v-model="formParams.proName" disabled type="input" />
            </el-form-item>
          </div>
          <!-- 项目模块 end -->
          <el-form-item label="提醒谁看：" prop="remindUserArr">
            <el-select
              clearable
              v-model="formParams.remindUserArr"
              placeholder="请选择提醒谁看"
              @focus="userInputFocus"
              class="w-full"
              multiple
            >
              <el-option
                v-for="(item, index) in selectOptionObj['remindUserArr']"
                :key="index"
                :label="item.label"
                :value="item.uuid"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="btnLoading"
            >保存</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParamUse"
      @ok="selectDialogData"
      @close="closeFn"
    ></SelectDialog>
  </div>
</template>
<script setup name="VisitDia">
import { reactive, getCurrentInstance } from 'vue'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import useUserStore from '@/store/modules/user'
import useCommonStore from '@/store/modules/common'
import {
  getDetailTactlistByCactName,
  visitUpdateCustomer
} from '@/api/customerManage/customerList'
import { addManage } from '@/api/system/notice'
import { addVisit } from '@/api/visit/visit'
import { format } from 'date-fns'
import { validatePhoneNegative } from '@/utils/validate'
const commonStore = useCommonStore()
const userStore = useUserStore()
const { proxy } = getCurrentInstance()
const props = defineProps({
  // 弹出框是否显示
  dialogParam: {
    required: true
  }
})
const data = reactive({
  dialogVisible: false,
  formParams: {
    productId: []
  },
  productList: [],
  rulesForm: {
    customerName: [
      {
        required: true,
        message: '客户名称不能为空',
        trigger: ['change', 'blur']
      }
    ],
    status: [
      {
        required: true,
        message: '客户状态不能为空',
        trigger: ['change', 'blur']
      }
    ],
    linkId: [
      {
        required: true,
        message: '客户联系人不能为空',
        trigger: ['change', 'blur']
      }
    ],
    // 联系人电话
    mainContactPhone: [{ validator: validatePhoneNegative, trigger: 'blur' }],
    proName: [
      {
        required: true,
        message: '项目名称不能为空',
        trigger: ['change', 'blur']
      }
    ],
    orderTitle: [
      {
        required: true,
        message: '订单名称不能为空',
        trigger: ['change', 'blur']
      }
    ],
    productId: [
      {
        required: true,
        message: '订单产品不能为空',
        trigger: ['change', 'blur']
      }
    ]
  },
  diaTitle: '新建回访',
  dialogParamUse: {}, //选择人员弹出框
  selectOptionObj: {}, // 提醒谁看
  msgData: null //消息推送参数
})
const {
  dialogVisible,
  formParams,
  productList,
  rulesForm,
  diaTitle,
  dialogParamUse,
  selectOptionObj,
  msgData
} = toRefs(data)
const { followup_method, customer_status, business_stage } = proxy.useDict(
  'followup_method',
  'customer_status',
  'business_stage'
)
const btnLoading = ref(false)
const serviceType = ref('0') // 业务类型
watch(
  () => props.dialogParam,
  () => {
    if (JSON.stringify(props.dialogParam) != '{}') {
      // console.log(props.dialogParam, 'props.dialogParam')
      proxy.resetForm('ruleFormRef')
      init()
    }
  },
  {
    deep: true,
    immediate: true
  }
)
watchEffect(() => {
  let initContactName = props.dialogParam.mainContactName
    ? props.dialogParam.mainContactName
    : ''
  let initContactPhone = props.dialogParam.mainContactPhone
    ? props.dialogParam.mainContactPhone
    : ''
  let initAddress = props.dialogParam.address ? props.dialogParam.address : ''
  let newContactName = formParams.value.mainContactName
    ? formParams.value.mainContactName
    : ''
  let newContactPhone = formParams.value.mainContactPhone
    ? formParams.value.mainContactPhone
    : ''
  let newAddress = formParams.value.address ? formParams.value.address : ''
  if (
    newContactName == initContactName &&
    newContactPhone == initContactPhone &&
    initAddress == newAddress
  ) {
    formParams.value.renew = false
  } else {
    formParams.value.renew = true
  }
})
async function init() {
  dialogVisible.value = props.dialogParam.isVisible
  formParams.value = {
    ...props.dialogParam,
    orderId: props.dialogParam.businessId
  }
  productList.value = JSON.parse(
    JSON.stringify(
      props.dialogParam?.productList ? props.dialogParam?.productList : []
    )
  )
  formParams.value.productIdArr = props.dialogParam?.productId
    ? [props.dialogParam?.productId]
    : []
  if (
    props.dialogParam?.remindUserArr &&
    props.dialogParam.remindUserArr.length > 0
  ) {
    formParams.value.remindUserArr = props.dialogParam?.remindUserArr
      ? props.dialogParam?.remindUserArr.map(e => {
          return `U${e}`
        })
      : []
    selectOptionObj.value['remindUserArr'] = formParams.value.remindUserArr.map(
      (e, i) => {
        return {
          uuid: e,
          label: props.dialogParam.remindUserNameArr[i]
        }
      }
    )
  }
  diaTitle.value = props.dialogParam.diaTitle
    ? props.dialogParam.diaTitle
    : '新建回访'
  fileList.value = props.dialogParam.sysAttachFiles
    ? props.dialogParam.sysAttachFiles
    : []
  if (
    props.dialogParam.tableName == 'biz_customer' ||
    props.dialogParam.tableName == 'ord_business_opportunity'
  ) {
    //获取联系人
    contactsOptions.value = [
      { contactName: props.dialogParam.linkName, id: props.dialogParam.linkId }
    ]
  }
}
/** 推送消息url 整理 */
const followUrl = type => {
  let pushUrl,
    pushBusinessId,
    id = props.dialogParam.businessId
  switch (type) {
    case 'ord_order':
      pushBusinessId = '销售订单-回访-' + id
      serviceType.value = '14'
      pushUrl = `/quality/service/visitList?id=${id}`
      break
    case 'ord_purchase_order':
      pushBusinessId = '采购订单-回访-' + id
      serviceType.value = '13'
      pushUrl = `/source/sourceModules/purchaseOrderDetails?purchaseOrderId=${id}&tabPane=FollowUpList`
      break
    case 'ord_inner_order':
      pushBusinessId = '内部订单-回访-' + id
      serviceType.value = '17'
      pushUrl = `/source/sourceModules/innerOrderDetails?innerOrderId=${id}&tabPane=FollowUpList`
      break
    case 'biz_customer':
      // 客户模块
      pushUrl = `/customerManage/customerModules/customerDetails?customerId=${id}&tabPane=follow`
      pushBusinessId = '客户-回访-' + id
      serviceType.value = '2'
      break
    case 'ord_project':
      // 项目模块
      pushUrl = `/sales/projectManage/projectDetails?id=${id}&tabPane=4`
      serviceType.value = '0'
      pushBusinessId = '项目-回访-' + id
      break
    case 'biz_contact':
      // 联系人模块
      pushUrl = `/customerManage/contactsModules/contactsDetails?contactsId=${id}&tabPane=follow`
      serviceType.value = '12'
      pushBusinessId = '联系人-回访-' + id
      break
    case 'ord_business_opportunity':
      //商机模块
      pushUrl = `/sales/businessManage/businessDetails?id=${id}&tabPane=3`
      serviceType.value = '16'
      pushBusinessId = '商机-回访-' + id
      break
  }
  return { url: pushUrl, businessId: pushBusinessId }
}
// 保存
const onSubmit = () => {
  proxy.$refs['ruleFormRef'].validate(async (valid, done, msg) => {
    if (valid) {
      if (!formParams.value.type) {
        proxy.$modal.msgError('回访方式不能为空')
        return false
      }
      if (!formParams.value.followTime) {
        proxy.$modal.msgError('回访时间不能为空')
        return false
      }
      if (!formParams.value.content) {
        proxy.$modal.msgError('回访内容不能为空')
        return false
      }
      let param = JSON.parse(JSON.stringify(formParams.value))
      param.sysAttachFiles = fileList.value || []
      delete param.isVisible
      delete param.businessType
      delete param.fileList
      let { url, businessId } = followUrl(props.dialogParam.tableName)
      if (param.remindUserArr?.length > 0) {
        param.remindUserArr = param.remindUserArr.map(e => {
          return e.replace(/U/gi, '')
        })
      }
      bidOpeningMsg()
      // const resp = bidOpeningMsg()
      // if (!resp) {
      //   return
      // }
      // btnLoading.value = true
      try {
        if (param.renew) {
          console.log('更新==》')
          visitUpdateCustomer(param)
        }
        const followupRes = await addVisit(param)
        if (followupRes.code === 200) {
          proxy.$emit('ok', followupRes)
          proxy.$modal.msgSuccess('操作成功')
          btnLoading.value = false
          msgData.value.url = url
          msgData.value.businessId = businessId
          if (
            formParams.value.remindUserArr &&
            formParams.value.remindUserArr.length > 0
          ) {
            addManage(msgData.value)
          }
          handleClose()
        }
      } catch (error) {
        btnLoading.value = false
      }
    }
  })
}
/*** 文件上传 start */
let fileList = ref([])
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/*****文件上传 end */
/***客户联系人数据  start*/
const contactsOptions = ref([])
/**
 * 客户联系人模糊搜索
 * @param val 当前输入的值
 */
async function queryContacts(val) {
  let params = {
    pageSize: 10,
    entId: formParams.value.businessId,
    contactName: val
  }
  await getDetailTactlistByCactName(params).then(res => {
    contactsOptions.value = res.data
  })
}
// 客户联系人选中事件
const contactsChange = val => {
  let newData = JSON.parse(JSON.stringify(contactsOptions.value))
  let obj = newData.filter(item => {
    return (item.id = val)
  })
  formParams.value.linkName = obj[0].contactName
}
/***客户联系人数据  end*/
/**** 项目负责人 模块 start */

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParamUse.value = {
    type: 'remindUserArr',
    title: '请选择提醒谁看',
    dataType: 'person',
    nodeKey: 'uuid',
    multiple: true,
    checkStrictly: false
  }
  dialogParamUse.value.isDialog = true
  dialogParamUse.value.defaultCheckedKeys = formParams.value.remindUserArr || []
}
/** 弹出框下拉框
 * 项目负责人
 * @param {*} val  selectDialog组件返回的值
 */
const selectDialogData = val => {
  switch (val.type) {
    case 'remindUserArr':
      // console.log('选择人员==》', val)
      selectOptionObj.value['remindUserArr'] = val.selectData
      formParams.value.remindUserNameArr = val.labelData
      formParams.value.remindUserArr = val.defaultCheckedKeys
        ? val.defaultCheckedKeys
        : null
      break
  }
}
const closeFn = val => {
  dialogParamUse.value.isDialog = false
}
/**** 项目负责人 模块 end */
const emit = defineEmits(['close'])
// 取消
function handleClose() {
  btnLoading.value = false
  dialogVisible.value = false
  formParams.value = {
    productIdArr: []
  }
  fileList.value = []
  emit('close', 'followUp')
}

const objTitle = {
  biz_customer: '客户详情',
  ord_project: '项目详情',
  ord_order: '订单详情',
  biz_contact: '联系人详情'
}

function bidOpeningMsg() {
  const objName = {
    biz_customer: formParams.value.customerName
      ? formParams.value.customerName
      : '',
    ord_project: formParams.value.proName ? formParams.value.proName : '',
    ord_order: formParams.value.orderTitle ? formParams.value.orderTitle : '',
    biz_contact: formParams.value.linkName ? formParams.value.linkName : '',
    ord_business_opportunity: formParams.value.customerName
      ? formParams.value.customerName
      : '',
    ord_purchase_order: formParams.value.orderTitle
      ? formParams.value.orderTitle
      : '',
    ord_inner_order: formParams.value.orderTitle
      ? formParams.value.orderTitle
      : ''
  }

  if (formParams.value.rebid === '0') {
    return true
  }
  const obj = {}
  let resp = true
  const time = formParams.value.followTime
    ? format(new Date(new Date().getTime()), 'yyyy-MM-dd 00:00:00')
    : ''
  obj.receiver = (
    formParams.value.remindUserArr ? formParams.value.remindUserArr : []
  )
    .toString()
    .replace(/U/gi, '')
  obj.content = `${objName[formParams.value.tableName]}回访：${
    formParams.value.content
  }`

  obj.sendTime = time
  obj.reminderMethod = '1'
  obj.impSign = '2'
  obj.serviceType = serviceType.value
  obj.urgFlag = '1'
  obj.receiverName = formParams.value.remindUserNameArr
    ? formParams.value.remindUserNameArr.toString()
    : []
  obj.followDate = formParams.value.followTime
  obj.urlName = '前往详情'
  obj.title = `关于${objName[formParams.value.tableName]}的回访提醒`
  obj.type = '0'
  obj.sender = userStore.user.nickName
  // 项目验收计划
  // const result = pushNotifications(obj, ['receiver'])
  // if (!result) {
  //   proxy.$modal.msgWarning('消息提醒存在未填内容，请先填写完整')
  //   resp = false
  // } else {
  msgData.value = obj
  // }
  // return resp
}
</script>
<style lang="scss">
.dialogStyle {
  border-radius: 10px;
  .el-dialog__header {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    @apply mr-0  text-#666 font-semibold bg-#f5f5f5;
  }
  .footer {
    @apply text-right border-t border-t-solid border-gray-100 pt-10px;
  }
}
</style>
